<template>
    <div>
        <div style="margin: 5px;text-align: center;">
            <el-input v-model="name" @click.enter.native="loadPost()" placeholder="请输入角色名称"
                style="width: 200px;margin-left: 5px;;" prefix-icon="el-icon-search"></el-input>
            <el-select v-model="register" @change="loadPost()" placeholder="请选择是否可注册"
                style="width: 200px;margin-left: 5px;;">
                <el-option v-for="item in registerData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="status" @change="loadPost()" placeholder="请选择角色状态"
                style="width: 200px;margin-left: 5px;;">
                <el-option v-for="item in statusData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>

            <el-button type="success" icon="el-icon-search" @click="loadPost()" circle
                style="margin-left: 5px;"></el-button>
            <el-button type="success" icon="el-icon-refresh" @click="resetParam" circle
                style="margin-left: 5px;"></el-button>
            <el-button type="primary" icon="el-icon-plus" @click="add" circle style="margin-left: 5px;"
                v-if="hasAuth('system:role-save')"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delHandle(null)" circle style="margin-left: 5px;"
                v-if="hasAuth('system:role-delete')" :disabled="delBtnStatus"></el-button>

        </div>
        <el-table :data="tableData" ref="multipleTable" tooltip-effect="dark" border style="width: 100%" stripe
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>

            <el-table-column label="角色名称" width="100" prop="name" align="center">
            </el-table-column>
            <el-table-column label="角色编码" width="100" prop="code" align="center">
            </el-table-column>
            <el-table-column label="角色描述" prop="remark" align="center">
            </el-table-column>
            <el-table-column label="角色注册状态" width="200" prop="register" align="center">
                <template slot-scope="scope">
                    <el-switch :value="scope.row.register == 1" active-text="正常" active-color="#13ce66"
                        inactive-color="#ff4949" inactive-text="注销"
                        @change="modRegisterStatus(scope.row.id)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="角色状态" width="200" prop="status" align="center">
                <template slot-scope="scope">
                    <el-switch :value="scope.row.status == 1" active-text="正常" active-color="#13ce66"
                        inactive-color="#ff4949" inactive-text="注销" @change="modStatus(scope.row.id)"></el-switch>
                </template>
            </el-table-column>

            <el-table-column label="注册时间" width="180" prop="createTime" align="center"
                :formatter="formatDate"></el-table-column>


            <el-table-column label="操作" width="300" align="center" fixed="right">
                <template v-slot="scope">
                    <el-button type="success" icon="el-icon-edit" @click="mod(scope.row)" circle
                        v-if="hasAuth('system:role-update')" style="margin-left: 5px;"></el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="delHandle(scope.row.id)" circle
                        style="margin-left: 5px;" v-if="hasAuth('system:role-delete')"></el-button>


                    <el-button type="primary" icon="el-icon-rank" @click="permHandle(scope.row.id)"
                        style="margin-left: 5px;" v-if="hasAuth('system:role-perm')">分配权限</el-button>


                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-size="pageSize" :page-sizes="[5, 20, 50, 100, 1000]" background
            layout="total,sizes,prev, pager, next,jumper" :total="total">
        </el-pagination>
        <el-dialog title="角色表单" :visible.sync="dialogVisible" width="600px" center>
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="form.name" style="width: 400px;"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" prop="code">
                    <el-input v-model="form.code" style="width: 400px;"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="remark">
                    <el-input v-model="form.remark" type="textarea" style="width: 400px;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="权限分配表单" :visible.sync="permDialogVisible" width="600px" center>
            <el-form ref="permForm" :model="permForm" label-width="150px">
                <el-tree :data="treeData" show-checkbox ref="navIds" node-key="id" :default-expand-all="true"
                    :check-stricity="true" :props="defaultProps">

                </el-tree>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="allSelect()">{{ btntext }}</el-button>
                <el-button @click="permDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitPerm()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import { mapGetters } from 'vuex'
export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Role',
    data() {
        return {
            user: JSON.parse(localStorage.getItem('CurUser')),
            tableData: [],

            total: 0,
            pageSize: 5,
            pageNum: 1,
            delBtnStatus: true,
            multipleSelection: [],
            name: '',
            register: '',
            status: 1,
            statusData: [
                {
                    id: 1,
                    name: "正常",
                },
                {
                    id: 0,
                    name: "禁用",
                },
            ],
            registerData: [
                {
                    id: 1,
                    name: "是",
                },
                {
                    id: 0,
                    name: "否",
                },
            ],
            dialogVisible: false,
            form: {
                name: '',
                code: '',
                remark: ""
            },
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                code: [
                    { required: true, message: '请输入编码', trigger: 'blur' },
                ],
                remark: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                ],
            },
            btntext: '全选',
            menuIds: [],
            allStatus: false,
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            permDialogVisible: false,
            permForm: {}
        }
    }, methods: {
        loadPost() {
            this.$axios.post('/role/listPage',
                {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    param: {
                        name: this.name + '',
                        register: this.register + '',
                        status: this.status + ''
                    }
                }).then(res => {
                   
                    if (res.code == 200) {
                        this.tableData = res.data
                        // console.log(res.data)
                        if (res.data.length == 0 && this.pageNum != 1) {
                            this.pageNum = 1;
                            this.loadPost()
                        }
                        this.total = res.total
                    }
                })
        },
        resetParam() {
            this.name = ''
            this.register = ''
            this.status = ''
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.pageNum = 1
            this.loadPost()
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.loadPost()
        },
        formatDate(row, column) {
            let data = row[column.property]
            if (data == null)
                return null
            let date = new Date(data)
            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        },
        add() {
            this.resetForm()
            this.dialogVisible = true

        },
        mod(row) {
            this.$axios.get('/role/info/' + row.id).then(res => {
                console.log(res)
                this.form = res.data.role
                this.dialogVisible = true
            })

        },
        save() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.doMod()
                    } else {
                        this.doSave()
                    }
                } else {
                    this.$message({
                        message: '校验失败',
                        type: 'warning'
                    })
                }
            })
        },
        doMod() {
            this.$axios.post('/role/update', this.form).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '修改成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                            this.dialogVisible = false
                            this.resetForm()
                        }
                    })
                } else {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    })
                }
            })

        },
        doSave() {
            this.$axios.post('/role/save', this.form).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '新增成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                            this.dialogVisible = false
                            this.resetForm()
                        }
                    })
                } else {
                    this.$message({
                        message: '新增失败',
                        type: 'error'
                    })
                }
            })
        },
        resetForm() {
            this.form = {
                name: '',
                code: '',
                remark: ""
            }
        },
        getMenuTree() {
            this.$axios.get('/menu/tree').then(res => {
               
                this.treeData = res.data
            })
        },
        permHandle(id) {

            this.permDialogVisible = true
            this.$axios.get('/role/info/' + id).then(res => {
               
                this.$refs.navIds.setCheckedKeys(res.data.ids)
                this.permForm = res.data.role
                this.btntext = "全选"
                this.allStatus = false
            })
        },
        getMenuIds() {
            this.$axios.get('/menu/ids').then(res => {
               
                this.menuIds = res.data
            })
        },
        allSelect() {
            if (!this.allStatus) {
                this.$refs.navIds.setCheckedKeys(this.menuIds)
                this.btntext = "取消全选"
                this.allStatus = true
            } else {
                this.$refs.navIds.setCheckedKeys([])
                this.btntext = "全选"
                this.allStatus = false
            }

        },
        submitPerm() {
            var ids = this.$refs.navIds.getCheckedKeys()
            this.$axios.post("/role/perm/" + this.permForm.id + '/' + ids).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '授权成功',
                        type: 'success',
                        onClose: () => {
                            this.permDialogVisible = false
                            this.loadPost()
                        }
                    })
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
            this.delBtnStatus = val.length == 0
        },
        delHandle(id) {
            var ids = []
            if (id) {
                //单删
                ids.push(id)
            } else {
                //批量删
                this.multipleSelection.forEach(item => {
                    ids.push(item.id)
                })
            }
            this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('/role/deleteBatch', ids, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(res => {
                   
                    if (res.code == 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.loadPost()
                    } else {
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消',
                    type: 'info'
                })
            })
        },
        modStatus(id) {
            this.$axios.post('/role/modStatus/' + id).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '操作成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                        }
                    }
                    )
                } else {
                    this.$message({
                        message: '操作失败',
                        type: 'error'
                    })


                }
            })
        },
        modRegisterStatus(id) {
            this.$axios.post('/role/modRegisterStatus/' + id).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '操作成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                        }
                    }
                    )
                } else {
                    this.$message({
                        message: '操作失败',
                        type: 'error'
                    })


                }
            })
        },
    },
    computed: {
        ...mapGetters([
            'hasAuth'
        ])
    }, mounted() {
        this.getMenuIds()
        this.getMenuTree()
        this.loadPost()
    },
}
</script>
<style scoped>
.el-pagination {
    text-align: center;
    margin-top: 22px;
}
</style>